<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox } from 'element-plus'

import { Table } from '@/components/Table'
import {
  adminCsIncomeAddApi,
  adminCsIncomeDelApi,
  adminCsIncomeEditApi,
  adminCsIncomeListApi,
  adminCsIncomeEditStatusApi
} from '@/api/cs/income'
import { TableData } from '@/api/cs/income/types'

import { ucOrgListApi } from '@/api/uc/org'
import { ucUserListAdminApi } from '@/api/uc/user'
import { adminCsOrderListApi } from '@/api/cs/order'

import { useTable } from '@/hooks/web/useTableTest'
import { ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

// const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
// const iconDel = useIcon({ icon: 'ep:delete' })
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: TableData[]
  },
  any
>({
  getListApi: adminCsIncomeListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'income_id',
    label: '主键',
    width: 60,
    search: {
      show: true
    }
  },
  {
    field: 'income_sn',
    label: '入款单编号',
    search: {
      show: true
    }
  },
  {
    field: 'order_id',
    label: '关联订单',
    table: {
      show: false
    },
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: adminCsOrderListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择订单（双击选择）',
        nameField: 'order_sn',
        valueField: 'order_id',
        crudSchemas: [
          {
            field: 'order_id',
            label: '订单ID',
            fixed: 'left',
            search: {
              show: true
            }
          },
          {
            field: 'order_sn',
            label: '订单编号',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    }
  },
  {
    field: 'order_sn',
    label: '订单编号',
    width: 170
  },
  {
    field: 'org_id',
    label: '组织ID',
    table: {
      show: false
    },
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucOrgListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择组织（双击选择）',
        nameField: 'org_name',
        relNameField: 'org_name',
        valueField: 'org_id',
        relValueField: 'org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '组织名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucOrgListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择组织（双击选择）',
        nameField: 'org_name',
        relNameField: 'org_name',
        valueField: 'org_id',
        relValueField: 'org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '组织名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      }
    }
  },
  {
    field: 'org_name',
    label: '组织名称',
    form: {
      show: false
    }
  },
  {
    field: 'shop_name',
    label: '店铺名称',
    form: {
      show: false
    }
  },
  {
    field: 'user_id',
    label: '用户ID',
    table: {
      show: false
    },
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucUserListAdminApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择创建人（双击选择）',
        nameField: 'user_name',
        relNameField: 'nickname',
        valueField: 'user_id',
        relValueField: 'user_id',
        crudSchemas: [
          {
            field: 'nickname',
            label: '姓名',
            search: {
              show: true
            }
          },
          {
            field: 'username',
            label: '用户名',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucUserListAdminApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择创建人（双击选择）',
        nameField: 'user_name',
        relNameField: 'nickname',
        valueField: 'user_id',
        relValueField: 'user_id',
        crudSchemas: [
          {
            field: 'nickname',
            label: '姓名',
            search: {
              show: true
            }
          },
          {
            field: 'username',
            label: '用户名',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    }
  },
  {
    field: 'user_name',
    label: '用户姓名'
  },
  {
    field: 'amount',
    label: '金额'
  },
  {
    field: 'status',
    label: '状态',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return cellValue != '0' ? getDictLabel('cs_income_status', cellValue) : ' '
    },
    form: {
      component: 'Select',
      componentProps: {
        options: dict.cs_income_status
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.cs_income_status
      },
      show: true
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 180
  },
  {
    field: 'action',
    width: 300,
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: TableData = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {}
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.income_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const apiDel = async (income_id) => {
  let delRes = await adminCsIncomeDelApi({ income_id: income_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const loading = ref(false)

const save = async (type = actionType.value) => {
  const edit = unref(editRef)
  switch (type) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          let res = await adminCsIncomeEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })

      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          let res = await adminCsIncomeAddApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'examine':
      ElMessageBox.confirm('请确认这笔金额已到账?', '审核', {
        confirmButtonText: '确认到账',
        cancelButtonText: '关闭',
        type: 'warning'
      })
        .then(async () => {
          let res = await adminCsIncomeEditStatusApi({
            status: '2',
            income_id: tableObject.currentRow.income_id
          })
            .catch(() => {})
            .finally(() => {})
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        })
        .catch(() => {})
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="success" :icon="iconSee" @click="action('see', row)" title="查看详情">
          查看详情
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton
        v-if="actionType == 'edit' || actionType == 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton
        v-if="actionType == 'see' && tableObject.currentRow.status == true"
        type="primary"
        @click="save('examine')"
      >
        审核
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
